package com.toy.controller.admin;

import com.toy.entity.User;
import com.toy.exception.ToyMallException;
import com.toy.form.UserLoginForm;
import com.toy.form.UserRegisterForm;
import com.toy.result.ResponseEnum;
import com.toy.service.AdminService;
import com.toy.vo.PageResult;
import com.toy.vo.SysResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author tystart
 * @create 2022-09-08-8:56
 */
@RestController
@CrossOrigin
@RequestMapping("/admin")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public SysResult login(@RequestBody UserLoginForm userLoginForm, BindingResult bindingResult){
        //非空校验
        if (bindingResult.hasErrors()){
            log.info("【管理员登录】用户信息不能为空");
            throw new ToyMallException(ResponseEnum.USER_INFO_NULL);
        }
        try {
            //根据用户名和密码判断是否成功
            String token = adminService.findUserByUp(userLoginForm);

            //int num = 1/0;
            if(StringUtils.hasLength(token)){
                return SysResult.success(token);
            }else {
                return SysResult.fail();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.fail();
        }
    }

    @GetMapping("/list")
    public SysResult findUserByPage(PageResult pageResult){
        PageResult userByPage = adminService.findUserByPage(pageResult);
        return SysResult.success(userByPage);
    }

    @PutMapping("/status/{id}/{role}")
    public SysResult updateRole(User user) {
        adminService.updateRole(user);
        return SysResult.success();
    }

    @RequestMapping("/addUser")
    public SysResult addUser(@RequestBody UserRegisterForm userRegisterForm, BindingResult bindingResult){
        //非空校验
        if (bindingResult.hasErrors()){
            log.info("【添加用户】用户信息不能为空");
            throw new ToyMallException(ResponseEnum.USER_INFO_NULL);
        }
        adminService.addUser(userRegisterForm);
        return SysResult.success();
    }

    @GetMapping("/{id}")
    public SysResult queryUserById(@PathVariable Integer id){
        User user = adminService.findUserById(id);
        return SysResult.success(user);
    }

    @PutMapping("/updateUser")
    public SysResult updateUser(@RequestBody User user){
        adminService.updateU(user);
        return SysResult.success();
    }

    @DeleteMapping("/{id}")
    public SysResult deleteUserById(@PathVariable Integer id) {
        adminService.deleteUserById(id);
        return SysResult.success();
    }

}
